<?php
namespace app\index\controller;

class Topic {
	public function index() {
		$topic_id = input('get.topic_id');
		if ($topic_id != null) {
			$ctopic = model('Topic');
			$topic_data = $ctopic::where('id', $topic_id)->find();
			$topic_list = $ctopic::field('id, short_title, able')->select();

			$ctopic_reply = model('TopicReply');
			$replys_data = $ctopic_reply::where('tid', $topic_id)->order('create_time desc')->select();

			if ($topic_data != null) {
				return view('index/topic', [
							'topic' => $topic_data,
							'topic_list' => $topic_list,
							'replys' => $replys_data
						]);
			}
		}
	}

	public function addReply() {
		$topic_reply = input('post.content');
		$topic_id = input('get.topic_id');
		$if_at = input('post.if_at');
		$at_list = input('post.at_list/a');
		$user_id = input('session.user_id');
		if ($topic_reply and $topic_id and $user_id) {
			$ctopic_reply = model('TopicReply');
			$reply_data = $ctopic_reply::where('tid', $topic_id)->where('uid', $user_id)->select();
			$if_same = false;
			if ($reply_data != null) {
				foreach ($reply_data as $reply) {
					if($reply->content == $topic_reply) {
						$if_same = true;
					}
				}
			}

			if(!$if_same) {
				$ctopic_reply->data([
					'tid' => $topic_id,
					'uid' => $user_id,
					'content' => $topic_reply
				]);
				$ctopic_reply->save();

				
				$this->addMessageList($ctopic_reply->id, $topic_id, 6);
				
				
				if ($if_at == 'true') {
					$this->addAtList($at_list, $ctopic_reply->id);
				}

				return json([
	                'status' => 'success',
	                'message' => '提交成功！',
	                'data' =>  null
	            ]);
			}
			else {
				return json([
	                'status' => 'error',
	                'message' => '不能发布重复内容！',
	                'data' =>  null
	            ]);
			}		
		}
		else {
			return json([
	                'status' => 'error',
	                'message' => '发表失败，请重试！',
	                'data' =>  null
	            ]);
		}
	}

	private function addAtList($at_list, $sender_id) {
		$cmsglist = model('Msglist');
		$data_list = array();
		if ($at_list) {
			foreach ($at_list as $at) {
				$data = array();
				$data['sender'] = $sender_id;
				$data['receiver'] = $at;
				$data['type'] = 0;
				array_push($data_list, $data);
			}
			$cmsglist->isUpdate(false)->saveAll($data_list);
		}
	}

	private function addMessageList($sender_id, $topic_id, $type) {
		$ctopic = model('Topic');
		$topic_data = $ctopic::where('id', $topic_id)->field('uid')->find();
		$cmsglist = model('Msglist');
		$cmsglist->data([
			'sender' => $sender_id,
			'receiver' => $topic_data->uid,
			'type' => $type
		]);
		$cmsglist->save();
	}
}